package fr.imag.m2pgi.m2m.geoloc.visu3D;

import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.HashMap;

import org.fusesource.hawtbuf.Buffer;
import org.fusesource.hawtbuf.UTF8Buffer;
import org.fusesource.mqtt.client.Callback;
import org.fusesource.mqtt.client.CallbackConnection;
import org.fusesource.mqtt.client.Listener;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;

public class MeasureRetriever implements Listener {
  
  private Visualizer visu;
  private MQTT mqtt;
  private CallbackConnection conn;
  
  public MeasureRetriever(Visualizer visual, String address, int port) throws URISyntaxException {
    this.visu = visual;
    mqtt = new MQTT();
    mqtt.setHost(address,port);
    System.out.println("cons");
    conn = mqtt.callbackConnection();
    conn.listener(this);
    conn.connect(new Callback<Void>() {

      public void onSuccess(Void arg0) {
        System.out.println("Subscriber connected");
      }

      public void onFailure(Throwable arg0) {
        arg0.printStackTrace();
      }
    });
    
    Topic[] subs = new Topic[1];
    subs[0] = new Topic("/geoloc",QoS.AT_LEAST_ONCE);
    conn.subscribe(subs, new Callback<byte[]>() {

      public void onFailure(Throwable arg0) {

      }

      public void onSuccess(byte[] arg0) {
        System.out.println("[SUB] SUBSCRIBE");

      }
    });
  }

  public void onConnected() {
    
  }

  public void onDisconnected() {
    // TODO Auto-generated method stub
    
  }

  public void onFailure(Throwable arg0) {
    // TODO Auto-generated method stub
    
  }

  public void onPublish(UTF8Buffer topic, Buffer payload, Runnable ack) {
    System.out.println("Received data");
    ByteBuffer buffer = payload.toByteBuffer();
    int z = buffer.getInt();
    HashMap<Double, Integer> data = new HashMap<Double, Integer>();
    while(buffer.hasRemaining()) {
      data.put(buffer.getDouble(), buffer.getInt());
    }
    visu.addMeasure(data, z);
    ack.run();
  }

}
